package com.study.java.dao.impl;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.study.java.dao.UserDao;
import com.study.java.domain.User;
import com.study.java.utils.DOM4JUtils;
import com.study.java.utils.DateConverterUtils;

/**
* @Name: UserDaoImpl
* @Description: XXX
* @Author: XXX
* @CreateDate: 2017-3-10 上午9:54:06 
* @Version: V1.0
 */
public class UserDaoImpl implements UserDao {

	public User getUserByUsername(String username) {
		User user = null ;
		//1、获取domcument对象
		Document document = DOM4JUtils.getDocument() ;
		//2、使用xpath获取指定的user节点元素
		Element userElement = (Element) document.selectSingleNode("//user[@username='"+ username +"']") ;
		if(userElement != null) {
			//3、将获取到的user节点元素中的属性值放入到user-bean中
			user = new User() ;
			user.setUsername(userElement.valueOf("@username")) ;
			user.setPassword(userElement.valueOf("@password")) ;
			//将字符串转换成日期类型
			user.setBirthday(DateConverterUtils.parse(userElement.valueOf("@birthday"))) ;
			user.setEmail(userElement.valueOf("@email")) ;
		}
		//4、返回查询结果
		return user;
	}

	public User getUserByUsernameAndPassword(String username, String password) {
		User user = null ;
		//1、获取domcument对象
		Document document = DOM4JUtils.getDocument() ;
		//2、使用xpath获取指定的user节点元素
		Element userElement = 
				(Element) document.selectSingleNode("//user[@username='"+ username +"' and @password='"+ password +"']") ;
		if(userElement != null) {
			//3、将获取到的user节点元素中的属性值放入到user-bean中
			user = new User() ;
			user.setUsername(userElement.valueOf("@username")) ;
			user.setPassword(userElement.valueOf("@password")) ;
			//将字符串转换成日期类型
			user.setBirthday(DateConverterUtils.parse(userElement.valueOf("@birthday"))) ;
			user.setEmail(userElement.valueOf("@email")) ;
		}
		//4、返回查询结果
		return user;
	}

	public void addUser(User user) {
		//1、获取document对象
		Document document = DOM4JUtils.getDocument() ;
		//2、获取根节点元素
		Element rootElement = document.getRootElement() ;
		//3、创建新user节点元素，将user-bean中的属性值设置到user节点的属性中
		Element newUserElement = DocumentHelper.createElement("user") ;
		newUserElement.addAttribute("username", user.getUsername()) ;
		newUserElement.addAttribute("password", user.getPassword()) ;
		newUserElement.addAttribute("birthday", DateConverterUtils.format(user.getBirthday())) ;
		newUserElement.addAttribute("email", user.getEmail()) ;
		//4、加入新节点
		rootElement.add(newUserElement) ;
		//5、写回到xml
		DOM4JUtils.writeXML(document) ;
	}

}
